package com.asc.ascoa;

import com.util.crypto.CryptoSystemClient;
import com.util.crypto.CryptoSystemServer;
import com.util.database.DatabaseManager;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "Login", value = "/login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");

        String error = null;

        String password = request.getParameter("password");

        DatabaseManager databaseManager = null;

        try {
            databaseManager = new DatabaseManager();
        } catch (ClassNotFoundException e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        } catch (SQLException e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        }

        try {
            ResultSet resultSet = databaseManager.executeQuery("SELECT `password` FROM `user` WHERE `username`=\"" + username + "\"");
            if (resultSet.next() && CryptoSystemServer.decry(resultSet.getString(1)).equals(password)) error = null;
            else error += "wrong username or password";

        } catch (SQLException e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        } catch (Exception e) {
            error += e + "\n";
            throw new RuntimeException(e);
        }

        //response
        if (error != null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");

            out.println("<h1>ERROR:" + error + "</h1>");
            out.println("</body></html>");
        }
        else response.sendRedirect("SendEmail.jsp?username=" + request.getParameter("username"));
    }
}
